[id].ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { defineEventHandler, EventHandlerRequest } from 'h3';
  2. import { DB } from '~~/server/db/DB';
  3. import { createErrorResponse, createSuccessResponse, IResponse } from '~~/server/utils/response';
  4. import { IChannel } from '../channel/[id]';
  5. export interface IArticle {
  6. id: number;
  7. model_id: number;
  8. channel_id: number;
  9. title: string;
  10. desc: string;
  11. image: string,
  12. video?: string,
  13. images: string;
  14. seotitle: string;
  15. keywords: string;
  16. description: string;
  17. tags: string;
  18. diyname: string;
  19. publishtime: number;
  20. createtime: number;
  21. views: number;
  22. content: string;
  23. channel: IChannel;
  24. }
  25. export default defineEventHandler<EventHandlerRequest, Promise<IResponse<IArticle>>>(async (event) => {
  26. try {
  27. const id = event.context.params?.id;
  28. if (!id)
  29. return createErrorResponse('分类ID不能为空');
  30. const article = await DB.table('pr_cms_archives')
  31. .where('id', id)
  32. .where('status', 'normal')
  33. .first();
  34. if (!article)
  35. return createErrorResponse('文章不存在');
  36. const channel = await DB.table('pr_cms_channel')
  37. .where('id', article.channel_id)
  38. .first();
  39. if (!channel)
  40. return createErrorResponse('分类不存在');
  41. article.channel = channel;
  42. // 2. 通过model_id从pr_cms_model表中获取table字段
  43. const model = await DB.table('pr_cms_model')
  44. .where('id', article.model_id)
  45. .select('table')
  46. .first();
  47. if (!model)
  48. return createErrorResponse('分类不存在');
  49. // 3. 通过table指定的表通过id查出content
  50. const content = await DB.table(`pr_${model.table}`)
  51. .where('id', id)
  52. .select('content')
  53. .first();
  54. // 4. 合并返回结果
  55. if (content && content['content']) {
  56. article.content = content['content'];
  57. }
  58. return createSuccessResponse(article);
  59. } catch (error) {
  60. return createErrorResponse(error);
  61. }
  62. });